﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace Platform.ObjectModel.Serializers
{
	public class JavaScriptStreamer : DataObjectStreamer
	{
		private Lazy<JsonSerializer> serializer;


		public JavaScriptStreamer()
			: base( Globals.Formatters.JSon )
		{
			this.serializer = new Lazy<JsonSerializer>( () => new JsonSerializer(), false );
		}

		public JsonSerializer Serializer
		{
			get { return this.serializer.Value; }
		}

		public override byte[] ToStream( object value )
		{
			if ( value == null )
				return null;

			using ( MemoryStream buffer = new MemoryStream() )
			{
				using ( JsonWriter writer = new JsonTextWriter( new StreamWriter( buffer ) ) )
				{
					this.Serializer.Serialize( writer, value );
					writer.Flush();
				}

				return buffer.ToArray();
			}
		}

		public override object FromStream( Type valueType, byte[] stream )
		{
			if ( stream == null || stream.Length == 0 )
				return null;

			using ( MemoryStream buffer = new MemoryStream( stream ) )
			{
				buffer.Position = 0;
				return this.Serializer.Deserialize( new StreamReader( buffer ), valueType );
			}
		}
	}

}
